from .base_strategy import BaseStrategy
import backtrader as bt
import backtrader.indicators as btind
import indicator.MyTTIndicator as Mytt
import indicator.myzhibiao as mmm


###
# 趋势回测，信号确认，则顺应需求继续开单
# 代码好像每写完整。
# 
# #
class MyStrategy(BaseStrategy):
    params = (
        ('fast_period', 20),
        ('slow_period', 120),
        ('stop_loss_pct', 5),  # 2% 止损
        ('reentry_window', 5),   # 5个交易日重新站上窗口
    )

 
    def __init__(self):
        super().__init__()

        # 初始化EMA指标
        self.ema_fast = btind.EMA(self.data.close,period=self.p.fast_period)
        self.ema_slow = btind.EMA(self.data.close,period=self.p.slow_period)
        
        # 交叉信号指标
        self.cross_up = btind.CrossUp(self.data.close, self.ema_fast)
        self.cross_down = btind.CrossDown(self.data.close,self.ema_fast)

        # 跟踪价格是否跌破EMA20
        self.below_ema_fast = False
        self.below_ema_fast_date = None
        
        # 跟踪订单和买卖信号
        self.order = None
        self.buy_price = None
        self.sell_price = None
        
        # 跟踪止损价格
        self.stop_loss_price = None

    def notify_order(self, order):
        super().notify_order(order)

    def notify_trade(self, trade):
        super().notify_trade(trade)

    def next(self):
        super().next()
        
        # 检查是否已经有持仓
        if self.position:
            # 检查止损条件
            if self.position.size > 0:  # 多头持仓
                if self.data.close[0] < self.stop_loss_price:
                    self.log(f'止损触发 @ {self.data.close[0]:.2f} (止损价: {self.stop_loss_price:.2f})')
                    self.close()
                if self.cross_down[0]:
                    self.log(f'止盈触发 @ {self.data.close[0]:.2f}')
                    self.close()
            elif self.position.size < 0:  # 空头持仓
                if self.data.close[0] > self.stop_loss_price:
                    self.log(f'止损触发 @ {self.data.close[0]:.2f} (止损价: {self.stop_loss_price:.2f})')
                    self.close()
                elif self.cross_up[0]:
                    self.log(f'止盈触发 @ {self.data.close[0]:.2f}')
                    self.close()
            return
        
        # 没有持仓时的逻辑
        current_price = self.data.close[0]
        
        # 检查是否在EMA120上方
        above_ema_slow = current_price > self.ema_slow[0]
        
        # 多头逻辑
        if above_ema_slow:
            # 检查是否跌破EMA20并在5日内重新站上
            if self.below_ema_fast and (len(self) - self.below_ema_fast_date) <= self.p.reentry_window:
                if current_price > self.ema_fast[0]:  # 重新站上EMA20
                    self.log(f'重新站上EMA20 @ {current_price:.2f}, 买入信号')
                    self.order = self.buy()
                    self.below_ema_fast = False
                    self.below_ema_fast_date = None
                    self.stop_loss_price = self.data.close[0] * (1 - self.p.stop_loss_pct / 100)
            elif self.cross_up[0]:  # 价格下穿均线  开始计算窗口数
                self.below_ema_fast = True
                self.below_ema_fast_date = len(self)
            elif current_price > self.ema_fast[0]:  # 价格在EMA20上方
                # self.log(f'价格在EMA20上方 @ {current_price:.2f}, 买入信号')
                # self.order = self.buy()
                pass
        
        # 空头逻辑 (在EMA120下方)
        else:
            # 检查是否跌破EMA20并在5日内重新站上(空头逻辑相反)
            if self.below_ema_fast and (len(self) - self.below_ema_fast_date) <= self.p.reentry_window:
                if current_price < self.ema_fast[0]:  # 重新跌破EMA20
                    self.log(f'重新跌破EMA20 @ {current_price:.2f}, 卖出信号')
                    self.order = self.sell()
                    self.below_ema_fast = False
                    self.below_ema_fast_date = None
                    self.stop_loss_price = self.data.close[0] * (1 + self.p.stop_loss_pct / 100)

            elif self.cross_down[0]:  # 价格站上EMA20
                self.below_ema_fast = True
                self.below_ema_fast_date = len(self)
            elif current_price < self.ema_fast[0]:  # 价格在EMA20下方
                # self.log(f'价格在EMA20下方 @ {current_price:.2f}, 卖出信号')
                # self.order = self.sell()
                pass